package cn.team.webSocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.team.entity.Message;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@ServerEndpoint("/chat/{username}")
@Component
public class ChatServerSocket {

    private static final ConcurrentHashMap<String,Session> websocketMap= new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        websocketMap.put(username,session);
        log.info("用户"+username+"以与服务器建立链接");
    }

    @OnClose
    public void onClose(Session session, @PathParam("username") String username) {
        websocketMap.remove(username);
        log.info("用户"+username+"以退出链接");
    }

    @OnMessage
    public void onMessage(Session session, String message) throws JSONException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        Message receiveMessage  = mapper.readValue(message, Message.class);
        System.out.println("收到:"+receiveMessage.getSendName()+":"+"发送给:"+receiveMessage.getReceiveName()+"的消息:"+receiveMessage.getContent());
        if(!receiveMessage.isGroup){
//            for(Map.Entry<String,Session> entry : websocketMap.entrySet()) {
//                entry.getValue().getAsyncRemote().sendObject(message);
//            }
            websocketMap.get(receiveMessage.getReceiveName()).getAsyncRemote().sendObject(message);
        }else{
             Session sendSession =  websocketMap.get(receiveMessage.getSendName());
             sendGroupMessage(sendSession, receiveMessage);
        }
    }

    @OnError
    public void onError(@PathParam("username") String username, Session session, Throwable error) {
        log.info("用户" + username + "的链接出现异常");
        websocketMap.remove(username);
        error.printStackTrace();
    }
    
    synchronized private void sendGroupMessage(Session session, Message msg) {
        try {
            session.getBasicRemote().sendObject(msg);
        } catch (IOException | EncodeException e) {
            e.printStackTrace();
        }
    }

}
